package com.xbj.voa.common.shiroAndJwt;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xbj.voa.exception.VoaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: 木火
 * @create: 2024-01-05
 * @description:JWT工具类
 * JWT:Json Web Token ,是为了在网络应用环境之间传递声明而执行的一种基于JSON的开放标准.Jwt一般用在身份提供者和服务提供者间传递被认证的用户身份信息,
 *  以便从资源服务器获取资源.也可以增加一些其他业务逻辑所必须得声明信息,该token可直接用于认证和加密
 **/
@Component
public class JwtUtil {
    private static Logger LOG = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 秘钥
     */
    @Value("${voa.jwt.secret}")
    private String secret;

    /**
     * 过期时间
     */
    @Value("${voa.jwt.expire}")
    private int expire;

    public String createToken(int userId){
        LOG.info("根据userId创建token开始,userId:"+userId);
        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire).toJdkDate();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        LOG.info("根据userId创建token结束,token:"+token);
        return token;
    }

    public int getUserId(String token){
        LOG.info("根据token获取userId开始,token:"+token);
        try {
            DecodedJWT decode = JWT.decode(token);
            Integer userId = decode.getClaim("userId").asInt();
            LOG.info("根据token获取userId结束,userId:"+userId);
            return userId;
        } catch (JWTDecodeException e) {
            LOG.info("根据token获取userId失败");
            throw new VoaException("令牌无效");
        }
    }

    public void verifierToken(String token){
        LOG.info("token校验开始");
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(token);

    }

}
